<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/15 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\components\oss;

use Yii;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云OSS 上传组件
 * @package common\components\oss
 */
class AliyunOss extends DefaultOss implements OssInterface
{
    // [阿里云OSS相关参数配置](https://help.aliyun.com/document_detail/88473.html?spm=a2c4g.11186623.6.1126.73ea25899gLjRg)
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
    private $_secretId = "<yourAccessKeyId>";
    private $_secretKey = "<yourAccessKeySecret>";

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private $_endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

    // 设置存储空间名称。
    private $_bucket = "<yourBucketName>";

    /** @var string 自定义访问域名 */
    private $_selfHost = "";

    /**
     * 初始化
     */
    public function init()
    {
        parent::init();
    }

    /**
     * 配置组件
     * @param array $config 配置数组
     */
    public function setConfig($config)
    {
        if (is_array($config)) {
            $this->_secretId = isset($config['secretId']) ? $config['secretId'] : '';
            $this->_secretKey = isset($config['secretKey']) ? $config['secretKey'] : '';
            $this->_endpoint = isset($config['endpoint']) ? $config['endpoint'] : '';
            $this->_bucket = isset($config['bucket']) ? $config['bucket'] : '';
            $this->_selfHost = isset($config['selfHost']) && !empty($config['selfHost']) ? trim($config['selfHost'], '/') . '/' : '';
        }
    }

    /**
     * 上传文件到OSS服务器
     * ~~~php
     * return [
     *  'code' => 1,
     *  'message' => '',
     *  'data' => [
     *      'path' => $this->_selfHost ? $this->_selfHost . $object : $res['info']['url'],
     *      'handler' => 'aliyunOss'
     *      ]
     *  ];
     * ~~~
     * @param string $object OSS保存的文件对象名称
     * @param object $file 要上传的本地文件对象
     * @param bool $deleteTempFile 是否删除临时文件.
     * @return mixed|string
     */
    public function upload($object, &$file, $deleteTempFile = true)
    {
        try {
            //$filePath 要上传的本地文件 由本地文件路径加文件名包括后缀组成，例如/users/local/file.txt
            $filePath = $file->tempName;
            $ossClient = new OssClient($this->_secretId, $this->_secretKey, $this->_endpoint);
            $res = $ossClient->uploadFile($this->_bucket, $object, $filePath);
            // 上传后删除temp文件
            if ($deleteTempFile === true) @unlink($filePath);
            if (isset($res['info']['http_code']) && isset($res['info']['url']) && $res['info']['http_code'] == 200 && !empty($res['info']['url'])) {
                return [
                    'code' => 1,
                    'message' => '',
                    'data' => [
                        'path' => $this->_selfHost ? $this->_selfHost . $object : $res['info']['url'],
                        'handler' => 'aliyunOss'
                    ]
                ];
            }
            return ['code' => 0, 'message' => '上传阿里云失败'];
        } catch (OssException $e) {
            return ['code' => 0, 'message' => $e->getMessage()];
        }
    }

    /**
     * 删除文件
     * @param string $object 要删除的OSS对象文件路径
     * @return mixed
     */
    public function delete($object)
    {
        try {
            $ossClient = new OssClient($this->_secretId, $this->_secretKey, $this->_endpoint);
            $res = $ossClient->deleteObject($this->_bucket, $object);
            return ['code' => 1, 'message' => '', 'data' => $res];
        } catch (OssException $e) {
            return ['code' => 0, 'message' => $e->getMessage()];
        }
    }
}
